package com.sams.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.sams.entity.Processmanage;
import com.sams.entity.SpotUpload;
import com.sams.entity.User;
import com.sams.service.BaseInfoService;
import com.sams.service.DataTotalService;
import com.sams.service.SchoolService;
import com.sams.service.SpotUploadService;
import com.sams.util.SamResult;

@RequestMapping("/spot")
@Controller
public class SpotUploadController {

	@Autowired
	private SpotUploadService service;
	@Autowired
	private BaseInfoService baseInfoService;
	@Autowired
	private DataTotalService dataTotalService;
	@Autowired
	private SchoolService schoolService;
	@RequestMapping("/list")
	public String listSpot(Integer currentPage,Model model,Integer schid,Integer status,
			Integer zid,String x,
			HttpServletRequest request,HttpSession session) {
		if(currentPage==null) {
			currentPage=1;
		}
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		//分页查询时，条件的来源 
		if(x!=null) {// 说明是分页信息
			//从session中获取条件
			status=(Integer)session.getAttribute("status");
			schid=(Integer)session.getAttribute("schid");
			zid=(Integer)session.getAttribute("zid");
		}
		//查询所有的乡镇
		if(user.getRoleid()==1 ||user.getRoleid()==2) {
			 //查询所有镇id
			model.addAttribute("xzList", baseInfoService.findById(user.getZid()));
		}else { 
			 model.addAttribute("xzList", dataTotalService.selectAllZhen());
		}
		PageInfo<SpotUpload> listSpot = service.ListSpot(currentPage, schid, status, user,zid);
		model.addAttribute("pageInfo", listSpot);
		session.setAttribute("schid",schid);
		session.setAttribute("status",status);
		session.setAttribute("zid", zid);
		//如果已选zid ，则需要回显它对应的学校，方便继续选择其他学校
		if(zid!=null && !zid.toString().equals("0")) {
			model.addAttribute("schoolListByZid",schoolService.selectSchoolByZid(zid));
		}
		return "spotupload";
		
	}
	@RequestMapping("/add")
	public String add(@RequestParam("titleimg") String titleimg
			,@RequestParam("propagateimg") MultipartFile propagateimg
			,@RequestParam("meetingimg") MultipartFile meetingimg
			,@RequestParam("namelistimg") MultipartFile namelistimg
			,@RequestParam("signatureimg") MultipartFile signatureimg
			,@RequestParam("schid")String schid
			,Model model
			,HttpServletRequest request) {
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		Properties properties = new Properties();
		   InputStream inputStream = ProcessmanagerController.class.getClassLoader().getResourceAsStream("db.properties");
		         try {
		   properties.load(inputStream);
		  } catch (IOException e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
		  }
		 File file=new File(properties.getProperty("imagePath")+File.separator+"spotupload");       
         if(!file.exists()){//如果文件夹不存在
 			file.mkdirs();//创建文件夹
 		}
         
         String newpropagateimg=getFileName(propagateimg.getOriginalFilename());
         String newmeetingimg=getFileName(meetingimg.getOriginalFilename());
         String newnamelistimg=getFileName(namelistimg.getOriginalFilename());
         String newsignatureimg=getFileName(signatureimg.getOriginalFilename());
         try {
			
			propagateimg.transferTo(new File(file.getPath()+File.separator+newpropagateimg));
			meetingimg.transferTo(new File(file.getPath()+File.separator+newmeetingimg));
			namelistimg.transferTo(new File(file.getPath()+File.separator+newnamelistimg));
			signatureimg.transferTo(new File(file.getPath()+File.separator+newsignatureimg));
			
			SpotUpload spot=new SpotUpload();
			spot.setTitle(titleimg);
			spot.setPropagateimg("spotupload/"+newpropagateimg);
			spot.setMeetingimg("spotupload/"+newmeetingimg);
			spot.setNamelistimg("spotupload/"+newnamelistimg);
			spot.setSignatureimg("spotupload/"+newsignatureimg);
			spot.setUid(user.getId());
			spot.setSchid(Integer.valueOf(schid));
			spot.setStatus(1);
			spot.setFinishdate(new Date());
			int count=service.add(spot);
			return "forward:/spot/list";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			model.addAttribute("error", "添加失败");
			return "error";
		}
				
	}
	//新文件名字
	public String getFileName(String fileName) {
			String filePrefix=fileName.substring(0,fileName.lastIndexOf('.'));
	        String fileSuffix=fileName.substring(fileName.lastIndexOf('.'), fileName.length());
	       return filePrefix+(int)(Math.random()*9000+1000)+fileSuffix;
	}
	
	//删除
	@RequestMapping("/delete")
	public String delete(Integer id,Model model) {
		
		int count = service.delete(id);
		if(count!=0) {
			return "forward:/spot/list";
		}else {
			model.addAttribute("error", "状态不为初稿,不能删除");
			return "error";
		}
		
	}
 
		 
		//修改查询
		@RequestMapping("/updateSpot")
		public String updateSpot(Integer id,HttpServletRequest request,Model model) {

			User user = (User) request.getSession().getAttribute("user");
			if (user == null) {
				model.addAttribute("error", "会话过期，请重新登录");
				return "error";
			}
			SpotUpload spot = service.findById(id);
			model.addAttribute("spot", spot);
			
			return "updateSpot";
			
		}
		//修改
		@RequestMapping("/update")
		public String update(@RequestParam("id") String id
				,@RequestParam("titleimg") String titleimg
				,@RequestParam("propagateimg") MultipartFile propagateimg
				,@RequestParam("meetingimg") MultipartFile meetingimg
				,@RequestParam("namelistimg") MultipartFile namelistimg
				,@RequestParam("signatureimg") MultipartFile signatureimg
				,@RequestParam("schid")String schid
				,Model model
				,HttpServletRequest request) {
			User user =  (User)request.getSession().getAttribute("user");
			if(user==null) {
				model.addAttribute("error", "会话过期，请重新登录");
				return "error";
			}
			Properties properties = new Properties();
			   InputStream inputStream = ProcessmanagerController.class.getClassLoader().getResourceAsStream("db.properties");
			         try {
			   properties.load(inputStream);
			  } catch (IOException e) {
			   // TODO Auto-generated catch block
			   e.printStackTrace();
			  }
			 File file=new File(properties.getProperty("imagePath")+File.separator+"spotupload");       
	         if(!file.exists()){//如果文件夹不存在
	 			file.mkdirs();//创建文件夹
	 		}
	         
	         String newpropagateimg=getFileName(propagateimg.getOriginalFilename());
	         String newmeetingimg=getFileName(meetingimg.getOriginalFilename());
	         String newnamelistimg=getFileName(namelistimg.getOriginalFilename());
	         String newsignatureimg=getFileName(signatureimg.getOriginalFilename());
	         try {
				
				propagateimg.transferTo(new File(file.getPath()+File.separator+newpropagateimg));
				meetingimg.transferTo(new File(file.getPath()+File.separator+newmeetingimg));
				namelistimg.transferTo(new File(file.getPath()+File.separator+newnamelistimg));
				signatureimg.transferTo(new File(file.getPath()+File.separator+newsignatureimg));
				
				SpotUpload spot=service.findById(Integer.valueOf(id));
				
				spot.setTitle(titleimg);
				spot.setPropagateimg("spotupload/"+newpropagateimg);
				spot.setMeetingimg("spotupload/"+newmeetingimg);
				spot.setNamelistimg("spotupload/"+newnamelistimg);
				spot.setSignatureimg("spotupload/"+newsignatureimg);
				spot.setUid(user.getId());
				spot.setSchid(Integer.valueOf(schid));				
				spot.setFinishdate(new Date());
				int count=service.update(spot);
				return "forward:/spot/list";
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				model.addAttribute("error", "修改失败");
				return "error";
			}
			
					
			
		}
		
		//上报
		@ResponseBody
		@RequestMapping("/report")
		public SamResult report(Integer id,Integer status,HttpSession session)
		{
			SamResult result = new SamResult();
			//获取用户的session
			User user =  (User)session.getAttribute("user");
			if(user==null) {
				//model.addAttribute("error", "会话过期，请重新登录");
				   result.setMsg("会话过期，请重新登录");
				   return result;
			}
			//验证该用户是否可以继续上报  
			// 对于学校账号，草稿状态的数据，可以继续操作
			// 对于镇账号  ，状态为1的数据 可以继续操作
			// 对于县账号，状态为2的数据  
			
			boolean flag=false;
			if(user.getRoleid()==1 && status==1) {
				flag=true;//可以继续
			}else if(user.getRoleid()==2 && status==2) {
				flag=true;
			}else if(user.getRoleid()==3 && status==3) {
				flag=true;
			}
		   if(flag) {
				int count =service.report(id);
				if(count>0) {
					 result.setData(count); //上报的数据条数
					 result.setStatus(200);
					 if(status==3) { //即将变为4  归档
						 result.setMsg("数据归档成功，已归档"+count+"条数据,可在数据查询菜单中查看");
					 }else {
						 result.setMsg("上报成功，已上报领导"+count+"条数据");
					 }
				}else {
					 
					 result.setData(count); //上报的数据条数
					 result.setStatus(-1);
					 result.setMsg("数据上报失败");
				}
				return result;
		   }else {
			   
				 result.setStatus(-1);
				 result.setMsg("对于当前状态的数据，您没有继续上报的权限。");
				 return result;
		   }
			
		}
		//撤销上报
		@ResponseBody
		@RequestMapping("/noreport")
		public SamResult noReport(Integer id,Integer status,HttpSession session)
		{
			SamResult result = new SamResult();
			//获取用户的session
			User user =  (User)session.getAttribute("user");
			if(user==null) {
				//model.addAttribute("error", "会话过期，请重新登录");
				   result.setMsg("会话过期，请重新登录");
				   return result;
			}
			boolean flag=false;
			if(user.getRoleid()==2 && status==2) {
				flag=true;//可以撤销
			}else if(user.getRoleid()==3 && status==3) {
				flag=true;
			} 
			
			if(flag) {
				int count =service.noreport(id);
				if(count>0) {
					 result.setData(count); //上报的数据条数
					 result.setStatus(200);
				 
					 result.setMsg("撤销成功，已撤销数据"+count+"条数据");
					 
				}else {
					 
					 result.setData(count); //上报的数据条数
					 result.setStatus(-1);
					 result.setMsg("数据上报失败");
				}
				return result;
			}else {
				 result.setStatus(-1);
				 result.setMsg("对于当前状态的数据，您没有撤销数据的权限。");
				 return result;
			}
			
		}
	
}
